package net.expectx.pay.merchant.controller;

import io.swagger.annotations.ApiOperation;
import net.expectx.common.single.base.BaseResult;
import net.expectx.common.single.util.Md5Util;
import net.expectx.pay.dao.bean.*;
import net.expectx.pay.merchant.common.AdminConstants;
import net.expectx.pay.rpc.api.MerchantApplicationService;
import net.expectx.pay.rpc.api.MerchantUserService;
import net.expectx.pay.rpc.api.PaymentChannelService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author hxs
 */
@Controller
@RequestMapping("/merchantUser")
public class MerchantUserController {
    private static final Integer FIFTY = 50;

    @Autowired
    private MerchantUserService merchantUserService;
    @Autowired
    private PaymentChannelService paymentChannelService;
    @Autowired
    private MerchantApplicationService merchantApplicationService;

    @ApiOperation(value = "修改密码")
    @RequestMapping(value = "/alterPassword", method = RequestMethod.GET)
    public String alterPassword() {
        return "merchantUser/alterPassword";
    }

    @ApiOperation(value = "修改手机号")
    @RequestMapping(value = "/alterMobild", method = RequestMethod.GET)
    public String alterMobild() {
        return "merchantUser/alterMobild";
    }

    @ApiOperation(value = "设置秘钥")
    @RequestMapping(value = "/setPrivateKey", method = RequestMethod.GET)
    public String setPrivateKey(ModelMap modelMap) {
        return "merchantUser/privateKey";
    }

    @ApiOperation(value = "商户中心")
    @RequestMapping(value = "/merchantCentre", method = RequestMethod.GET)
    public String merchantCentre() {
        return "merchantUser/merchantCentre";
    }

    @ApiOperation(value = "修改安全密码")
    @RequestMapping(value = "/alterSecurityPassword", method = RequestMethod.GET)
    public String alterSafetyPassword() {
        return "merchantUser/alterSecurityPassword";
    }

    @ApiOperation(value = "注册渠道列表")
    @RequestMapping(value = "/getPaymentChannels", method = RequestMethod.GET)
    @ResponseBody
    public Object getPaymentChannels(@RequestParam(required = false, defaultValue = "1", value = "page") int page,
                                     @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                                     HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>(16);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        String merchantNo=session.getAttribute("merchantNo").toString();

        MerchantApplicationExample merchantApplicationExample = new MerchantApplicationExample();
        MerchantApplicationExample.Criteria criteria = merchantApplicationExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        criteria.andMerchantNoEqualTo(merchantNo);
        List<MerchantApplication> merchantApplications = merchantApplicationService.selectByExample(merchantApplicationExample);

        List<Long> paymentChannelList = new ArrayList<>();
        for (MerchantApplication merchantApplication : merchantApplications) {
            String[] split = merchantApplication.getPaymentChannel().split(",");
            for (String s : split) {
                if (!paymentChannelList.contains(Long.valueOf(s))) {
                    paymentChannelList.add(Long.valueOf(s));
                }
            }
        }
        PaymentChannelExample paymentChannelExample = new PaymentChannelExample();
        PaymentChannelExample.Criteria criteria1 = paymentChannelExample.createCriteria();
        criteria1.andIsDeletedEqualTo(AdminConstants.NO);
        criteria1.andIdIn(paymentChannelList);
        List<PaymentChannel> paymentChannels = paymentChannelService.selectByExample(paymentChannelExample);

        long total = paymentChannelService.countByExample(paymentChannelExample);
        result.put("code", AdminConstants.LAYUI_DATA_OK);
        result.put("count", total);
        result.put("msg", "");
        result.put("data", paymentChannels);
        return result;
    }

    @ApiOperation(value = "修改密码")
    @RequestMapping(value = "/alterPassword", method = RequestMethod.POST)
    @ResponseBody
    public Object alterPassword(String oldpass, String newpass) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser = (MerchantUser) session.getAttribute("merchantUser");
        if (merchantUser.getPassword().toLowerCase().equals(Md5Util.md5(oldpass + merchantUser.getSalt()).toLowerCase())) {
            merchantUser.setPassword(Md5Util.md5(newpass + merchantUser.getSalt()));
            return merchantUserService.updateByPrimaryKey(merchantUser);
        }
        return new BaseResult(false, "原始密码错误", null);
    }

    @ApiOperation(value = "修改手机号")
    @RequestMapping(value = "/alterMobild", method = RequestMethod.POST)
    @ResponseBody
    public Object alterMobild(String mobile, String vercode) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser = (MerchantUser) session.getAttribute("merchantUser");
        merchantUser.setMobile(mobile);

        return merchantUserService.updateByPrimaryKey(merchantUser);
    }

    @ApiOperation(value = "设置秘钥")
    @RequestMapping(value = "/setPrivateKey", method = RequestMethod.POST)
    @ResponseBody
    public Object setPrivateKey() {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser = (MerchantUser) session.getAttribute("merchantUser");
        String key = UUID.randomUUID().toString().toLowerCase().replace("-", "");
        merchantUser.setPrivateKey(getEncrypt(key));
        return merchantUserService.updateByPrimaryKey(merchantUser);
    }

    @ApiOperation(value = "修改安全密码")
    @RequestMapping(value = "/alterSecurityPassword", method = RequestMethod.POST)
    @ResponseBody
    public Object alterSafetyPassword(String securityPass) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser = (MerchantUser) session.getAttribute("merchantUser");
        merchantUser.setSecurityPassword(Md5Util.md5(securityPass + merchantUser.getSalt()));
        return merchantUserService.updateByPrimaryKey(merchantUser);
    }

    public String getEncrypt(String key) {
        String encryptString = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
        char[] encrypt = encryptString.toCharArray();
        StringBuffer str = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < FIFTY; i++) {
            str.append(encrypt[random.nextInt(encrypt.length)]);
        }
        return str.toString() + key;
    }


}
